import datetime
import random
import traceback

import service
from flask import Flask, render_template, request

import support

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html', data={
        'total': '',
        'replies': '',
        'winner_index': -1
    })


@app.route('/get-reply-then-draw', methods=['post'])
def get_reply_then_draw():
    try:
        url = request.form.get("url")
        filter_time_str = request.form.get("filter_time")
        replies = service.get_reply(url, support.str_to_time(filter_time_str, '%Y-%m-%d'))
        reply_size = len(replies)

        return render_template('index.html', data={
            'replies': replies,
            'total': reply_size,
            'winner_index': random.randrange(0, reply_size)
        })

    except Exception as e:
        traceback.print_exc()
        return index()


if __name__ == '__main__':
    app.run()
